package org.yxjme.exjni_two.a;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.drawable.AnimationDrawable;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import org.yxjme.exjni_two.R;
import org.yxjme.exjni_two.RecordState;
import org.yxjme.exjni_two.i.CallBack;
import org.yxjme.exjni_two.u.SdcardUtil;
import org.yxjme.exjni_two.u.TimerCountUtil;
import org.yxjme.exjni_two.v.CameraSurfaceView;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

public class RecordVideoActivity extends AppCompatActivity {

    /*显示*/
    private CameraSurfaceView mRecordVideo;
    /*用于录制音频和视频。记录控件基于一个简单的状态机*/
    private MediaRecorder mediaRecorder ;
    private Camera camera ;
    private AnimationDrawable animation ;
    private Button btn_todo ;
    private ImageView im_anim ;
    private TextView tv_time ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_video);
        mRecordVideo  = findViewById(R.id.mRecordVideo);
        initView();
    }





    private void initView() {
        im_anim = findViewById(R.id.im_anim);
        animation = (AnimationDrawable) im_anim.getBackground();
        btn_todo = findViewById(R.id.btn_todo);
        tv_time = findViewById(R.id.tv_time);

        camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
        startContinuousAutoFocus();
        mRecordVideo.init(camera);
    }





    /**
     * 自定义MediaRecorder的录制参数
     */
    private void setConfig() {
        /*需要放在输出格式之前*/
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        //设置封装格式 默认是MP4
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        //音频编码
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        //图像编码
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        //声道
        mediaRecorder.setAudioChannels(1);
//        设置最大录像时间 单位：毫秒
        mediaRecorder.setMaxDuration(60 * 1000);
        //设置最大录制的大小60M 单位，字节
        mediaRecorder.setMaxFileSize(60 * 1024 * 1024);
        //再用44.1Hz采样率
        mediaRecorder.setAudioEncodingBitRate(22050);
        //设置帧率，该帧率必须是硬件支持的，可以通过Camera.CameraParameter.getSupportedPreviewFpsRange()方法获取相机支持的帧率
//        mediaRecorder.setVideoFrameRate(mFps);
        //设置码率
        mediaRecorder.setVideoEncodingBitRate(500 * 1024 * 8);
//        设置视频尺寸，通常搭配码率一起使用，可调整视频清晰度
        mediaRecorder.setVideoSize(1280, 720);
    }



    boolean startContinuousAutoFocus() {
        Camera.Parameters params = camera.getParameters();
        List<String> focusModes = params.getSupportedFocusModes();
        String  CAF_PICTURE = Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE,
                CAF_VIDEO = Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO,
                supportedMode = focusModes.contains(CAF_PICTURE) ? CAF_PICTURE : focusModes.contains(CAF_VIDEO) ? CAF_VIDEO : "";
        if (!supportedMode.equals("")) {
            params.setFocusMode(supportedMode);
            camera.setParameters(params);
            return true;
        }
        return false;
    }



    private void startRecordVideo() {
        if (mediaRecorder == null){
            mediaRecorder = new MediaRecorder() ;
        }

        if (camera!=null){
            camera.setDisplayOrientation(90);
            camera.unlock();
            mediaRecorder.setCamera(camera);
        }
        mediaRecorder.setOnErrorListener(new MyErrorListener());
        mediaRecorder.setOnInfoListener(new InfoListener());
        /*配置相关信息*/
        setConfig();
        /*录制视频位置*/
        mediaRecorder.setOutputFile(VideoFilePath());
        /*呈现出画面*/
        mediaRecorder.setPreviewDisplay(mRecordVideo.getHolder().getSurface());
        try {
            mediaRecorder.prepare();
            mediaRecorder.start();
            state = RecordState.recording ;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            changeBtnState();
            initTime();
        }
    }


    /**
     */
    private void changeBtnState() {
        switch (state){
            case recording:
                animation.start();
                btn_todo.setText("点击完成");
                break;
            case stop:
                btn_todo.setText("录制");
                animation.stop();
                break;
            case prepare:
                btn_todo.setText("录制");
                break;
        }
    }




    /**
     * 录制视频的路径
     *
     * @return
     */
    private String VideoFilePath() {
        String path= SdcardUtil.getRootFilePath(this) + File.separator + UUID.randomUUID()+".mp4";
        File file = new File(path) ;
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path ;
    }



    public void reset(){
        if (mediaRecorder!=null){
            mediaRecorder.stop();
            mediaRecorder.reset();   // You can reuse the object by going back to setAudioSource() step
            mediaRecorder.release(); // Now the object cannot be reused
            mediaRecorder = null;
        }
        state = RecordState.stop ;
        changeBtnState();

        timerCountUtil
                .setPause(true)
                .release();
        timerCountUtil = null;
    }


    /**
     * 销毁
     */
    public void release(){
        if (mediaRecorder!=null){
            mediaRecorder.stop();
            mediaRecorder.reset();   // You can reuse the object by going back to setAudioSource() step
            mediaRecorder.release(); // Now the object cannot be reused
            mediaRecorder = null;
        }

        if (camera!=null){
            camera.stopPreview();
            camera.release();
            camera = null ;
        }

        state = RecordState.stop ;
        changeBtnState();
    }


    /**
     * 录制状态
     *
     */
    private RecordState state = RecordState.prepare;
    public void restart() throws IOException {
        mediaRecorder.start();
        state = RecordState.recording ;
        changeBtnState();
    }


    private TimerCountUtil timerCountUtil ;
    public void initTime(){
        timerCountUtil = new TimerCountUtil();
        timerCountUtil.setCallBack(new CallBack() {
            @Override
            public void onResult(final Object o) {
                Log.v("[TimerCountUtil]->","Object="+o.toString()) ;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_time.setText(o.toString());
                    }
                });
            }

            @Override
            public void onError(String msg) {

            }
        }).start();
    }


    /**
     * 开始
     *
     * @param view
     */
    public void start(View view) throws IOException {
        switch (state){
            case prepare:
            case stop:
                startRecordVideo();
                break;
            case recording:
                reset();
                break;
        }
    }



    private class MyErrorListener implements MediaRecorder.OnErrorListener {

        @Override
        public void onError(MediaRecorder mr, int what, int extra) {

        }
    }


    private class InfoListener implements MediaRecorder.OnInfoListener {

        @Override
        public void onInfo(MediaRecorder mr, int what, int extra) {

        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        release();
        if (timerCountUtil!=null)
        timerCountUtil.release();
    }
}